package watcher

import (
	"github.com/shirou/gopsutil/disk"
	"time"
	"watcher/client/config"
)

type DiskWatcher struct {
	Done     chan struct{}
	Duration time.Duration
}

func (watcher *DiskWatcher) Watch() <-chan *WatchData {
	dataChan := make(chan *WatchData, 10)
	go watcher.watch(dataChan, watcher.Duration)
	return dataChan
}

func (watcher *DiskWatcher) watch(ch chan<- *WatchData, duration time.Duration) {
	defer close(ch)
	ticker := time.NewTicker(duration)
	for t := range ticker.C {
		select {
		case <-watcher.Done:
			ticker.Stop()
			break
		default:
			usage, err := disk.Usage("/")
			if err != nil {
				continue
			}
			ch <- &WatchData{
				Measurement: "disk",
				Time:        t,
				Fields: map[string]interface{}{
					"percent": usage.UsedPercent,
				},
			}
		}
	}
}

func (watcher *DiskWatcher) Close() {
	close(watcher.Done)
}

func NewDiskWatcher(conf config.Conf) (*DiskWatcher, error) {
	return &DiskWatcher{
		Done:     make(chan struct{}),
		Duration: conf.Duration,
	}, nil
}

var DiskRegister = func(conf config.Conf) (string, Watcher, error) {
	wt, err := NewDiskWatcher(conf)
	return "disk", wt, err
}
